package com.icongyou.enterprise.talent_analysis.service.impl;

import com.icongyou.enterprise.talent_analysis.entity.HrTemplatePreference;
import com.icongyou.enterprise.talent_analysis.event.TemplateChangeEvent;
import com.icongyou.enterprise.talent_analysis.mapper.HrTemplatePreferenceMapper;
import com.icongyou.enterprise.talent_analysis.service.HrTemplatePreferenceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * HR模板偏好服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class HrTemplatePreferenceServiceImpl implements HrTemplatePreferenceService {

    private final HrTemplatePreferenceMapper preferenceMapper;
    private final ApplicationEventPublisher eventPublisher;

    @Override
    public String getCurrentTemplateId(String hrUserId) {
        HrTemplatePreference preference = preferenceMapper.selectByHrUserId(hrUserId);
        if (preference == null) {
            return null;
        }
        
        return preference.getTemplateId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setCurrentTemplate(String hrUserId, String enterpriseId, String templateId) {
        String oldTemplateId = null;
        
        try {
            HrTemplatePreference existing = preferenceMapper.selectByHrUserId(hrUserId);
            
            // 记录旧模板ID
            if (existing != null) {
                oldTemplateId = existing.getTemplateId();
            }
            
            if (existing == null) {
                // 首次设置
                HrTemplatePreference preference = new HrTemplatePreference();
                preference.setId(UUID.randomUUID().toString());
                preference.setHrUserId(hrUserId);
                preference.setEnterpriseId(enterpriseId);
                preference.setTemplateId(templateId);
                preference.setLastUsedAt(LocalDateTime.now());
                preference.setCreatedAt(LocalDateTime.now());
                preference.setUpdatedAt(LocalDateTime.now());
                
                int result = preferenceMapper.insert(preference);
            } else {
                // 更新设置
                existing.setTemplateId(templateId);
                existing.setLastUsedAt(LocalDateTime.now());
                existing.setUpdatedAt(LocalDateTime.now());
                
                int result = preferenceMapper.updateByHrUserId(existing);
            }
            
            // 发布模板变更事件(仅当模板确实变化时)
            if (!isSameTemplate(oldTemplateId, templateId)) {
                TemplateChangeEvent event = new TemplateChangeEvent(
                    this,
                    hrUserId,
                    enterpriseId,
                    oldTemplateId,
                    templateId,
                    null  // 可以后续优化:查询该HR负责的学生列表
                );
                eventPublisher.publishEvent(event);
            }
        } catch (Exception e) {
            log.error("切换模板失败", e);
            throw e;
        }
    }
    
    /**
     * 判断两个模板ID是否相同(考虑null情况)
     */
    private boolean isSameTemplate(String template1, String template2) {
        if (template1 == null && template2 == null) {
            return true;
        }
        if (template1 == null || template2 == null) {
            return false;
        }
        return template1.equals(template2);
    }
}
